<?php
namespace app\index\controller;

use think\Controller;
use app\admin\model\NewsModel;
use app\admin\model\ClassModel;
use app\admin\model\LabelModel;
use app\admin\model\NewsLabelModel;
use app\admin\model\CommentModel;
use app\admin\model\ReplyModel;
use app\admin\model\MemberModel;
use app\admin\model\RecordModel;
/**
 * 博文
 * @author Alinejun666
 * Date 2018-8-23
 */
class News extends controller
{
    public function initialize()
    {
        // 验证登录是否过期
        $user = session('member');
        if (!empty($user)) {
            $diff = (int)time() - (int)strtotime($user['active_time']);
            if ($diff > 1800) {
                session("member", null);
            }else{
                session("member.active_time", date("Y-m-d H:i:s",time()));
            }
        }
    }

    public function index()
    {
        $news    = new NewsModel();
        $comment = new CommentModel();
        $class   = new ClassModel();
        $label   = new LabelModel();
        $newslabel = new NewsLabelModel();

        $class_id = input("param.class_id/d");
        $label_id = input("param.label_id/d");

		$where    = ['status' => 1];
		$order    = "top desc, news_id desc";
		$size     = 10;

        // 分类筛选
        if (!empty($class_id)) {
            $wherearr = [
                'status' => 1,
                'class_id' => $class_id,
            ];
            $classes = $class->get_info($wherearr);
            if (empty($classes)) {
                $this->error("分类不存在","/index/news/index");
                exit;
            }

            $where['class_id'] = $class_id;
        }
        // 标签筛选
        if (!empty($label_id)) {
            $wherearr = [
                'status' => 1,
                'label_id' => $label_id,
            ];            
            $labels = $label->get_info($wherearr);
            if (empty($labels)) {
                $this->error("标签不存在","/index/news/index");
                exit;
            }

            $arr = $newslabel->get_list(['label_id' => $label_id]);
            $news_arr = [];
            if (!empty($arr)) {
                foreach ($arr as $k => $v) {
                    $news_arr[] = $v['news_id'];
                }

                $where['news_id'] = $news_arr;
            }else{
                $where['news_id'] = -1;
            }
        }
		// 获取数据
		$data = $news->get_news_list($where, $order, "*", $size);
        $list = $data['list']['data'];

        foreach ($list as $k => $v) {
            // 分类名称
            $list[$k]['classname'] = $class->get_field(['class_id' => $v['class_id']], "name");
            
            // 评论数量
            $list[$k]['count_comment'] = $comment->get_count(['news_id' => $v['news_id']]);
        }

        $res = [
            'data' => $list,
            'page' => $data['page'],
            'count'=> $data['count'],
        ];

        // 分类名称
        if (!empty($classes)) {
            $res['classname'] = $classes['name'];
        }
        // 标签名称
        if (!empty($labels)) {
            $res['labelname'] = $labels['name'];
        }

		return $this->fetch('index', $res);
    }

    // 全文搜索
    public function select()
    {
        $news    = new NewsModel();
        $comment = new CommentModel();
        $class   = new ClassModel();
        $label   = new LabelModel();
        $newslabel = new NewsLabelModel();

        $words = input("param.q/s");

        $where = [];
        $where = ['status' => 1];
        $order = "news_id desc";
        $size  = 10;

        // 过滤关键词
        if (!empty($words)) {
            $words = filter_keyword($words);
        }

        // 获取数据
        $data = $news->select_news_list($where, $words, $order, "*", $size);
        $list = $data['list']['data'];

        foreach ($list as $k => $v) {
            $list[$k]['title'] = str_ireplace($words, "<em> ".$words." </em>", $v['title']);
            $list[$k]['desc']  = str_ireplace($words, "<em> ".$words." </em>", $v['desc']);

            // 分类名称
            $list[$k]['classname'] = $class->get_field(['class_id' => $v['class_id']], "name");
            
            // 评论数量
            $list[$k]['count_comment'] = $comment->get_count(['news_id' => $v['news_id']]);
        }

        $res = [
            'data' => $list,
            'page' => $data['page'],
            'count'=> $data['count'],
        ];

        // 关键词
        if (!empty($words)) {
            $res['words'] = $words;
        }

        return $this->fetch('index', $res);
    }

    public function info()
    {
        $news      = new NewsModel();
        $class     = new ClassModel();
        $label     = new LabelModel();
        $newslabel = new NewsLabelModel();
        $comment   = new CommentModel();
        $reply     = new ReplyModel();
        $member    = new MemberModel();
        $record    = new RecordModel();

    	$news_id = input("param.news_id/d");
    	if (empty($news_id)) {
    		$this->error("文章不存在");
    	}

        // 浏览记录
        $userinfo = session('member');
        if (!empty($userinfo)) {
            $where = [
                'news_id' => $news_id,
                'user_id' => $userinfo['user_id'],
            ];

            $res = $record->get_info($where);
            if ($res) {
                $where = [
                    'record_id'   => $res['record_id'],
                    'create_time' => date("Y-m-d H:i:s", time()),
                ];

                $record->save_data($where);
            }else{

                $record->insert_data($where);
            }
        }


    	// 查询文章
    	$info = $news::get($news_id);

        // 上下文
        $order = "top desc, news_id desc";
        $idarr = $news->get_list(['status' => 1], $order, "news_id, title");
        $prev  = $next = [];
        foreach ($idarr as $k => $v) {
            if ($news_id == $v['news_id']) {
                $prev = isset($idarr[$k-1])? $idarr[$k-1]: '';
                $next = isset($idarr[$k+1])? $idarr[$k+1]: '';
            }
        }

        // 增加浏览量
        $where = [
            'news_id' => $news_id,
            'scan'    => $info['scan']+1,
        ];
        $news->save_data($where);

    	// 获取分类
    	$classinfo = $class::get($info['class_id']);
    	$info['classname'] = $classinfo['name'];

    	// 获取标签
		$where  = ['news_id' => $news_id];
		$labels = $newslabel->get_list($where);
		if (!empty($labels)) {
			$label_arr = [];
			foreach ($labels as $k => $v) {
				$label_arr[] = $v['label_id'];
			}

			$where = "label_id IN (".implode(",", $label_arr).")";
			$res   = $label->get_list($where);

			$info['labels'] = $res;
		}

		// 会员信息
    	$user = session("member");
    	
        // 评论信息
        $comment_list = $comment->get_list(['news_id' => $news_id], "create_time desc");
        if (count($comment_list) > 0) {
            foreach ($comment_list as $k => $v) {
                // 会员信息
                $comment_list[$k]['userinfo'] = $member->get_info(['user_id' => $v['user_id']], "user_id, headpic, nickname");
                // 评论数
                $comment_list[$k]['discuss'] = $reply->get_count(['comment_id' => $v['comment_id']]);
            }

        }

        // 页面传参
    	$data = [
			'data' => $info,
            'prev' => $prev,
            'next' => $next,
			'member' => $user,
            'comments' => $comment_list,
		];

		return $this->fetch('info', $data);
    }

    public function comment()
    {

        if (request()->isAjax()) {
            $comment = new CommentModel();
            $reply   = new ReplyModel();

            // 入参
            $data  = input("param.");

            // 登录信息
            $user = session('member');
            if (empty($user)) {
                echo json_encode(msg_error("请先登录.."));exit;
            }else{
		        $diff = (int)time() - (int)strtotime($user['active_time']);
		        if ($diff > 1800) {
		            session("member", null);
                	echo json_encode(msg_error("登录已过期，请重新登录.."));exit;
		        }            	
            }

            // 频率检测
            $where = [
            	'user_id' => $user['user_id'],
            ];
            $order = "create_time desc";
            $field = "create_time";
            $info  = $comment->get_order_info($where, $order, $field);
	        $diff = (int)time() - (int)strtotime($info['create_time']);
	        if ($diff < 90) {
            	echo json_encode(msg_error("评论频率过快，请歇会儿再来.."));exit;
	        }

            $data  = input("param.");

            if (!empty($data['comment_id'])) {
                $where = [
                    'user_id'    => $user['user_id'],
                    'comment_id' => $data['comment_id'],
                    'reply_type' => $data['reply_type'],
                    'content'    => $data['content'],
                    'user_ip'    => get_client_ip(),
                ];
                if ($data['reply_type'] == 1) {
                    $where['reply_pid'] = $data['comment_id'];
                }else{
                    $where['reply_pid'] = $data['reply_id'];
                }

                // 回复
                $res = $reply->insert_data($where);
                if (isset($res['msg'])) {
                    echo json_encode($res);exit;
                }else{
                    echo json_encode(msg_success("回复成功"));exit;
                }

            }else{
                $where = [
                    'news_id' => $data['news_id'],
                    'title'   => $data['title'],
                    'user_ip' => get_client_ip(),
                    'user_id' => $user['user_id'],
                    'content' => $data['content'],
                ];

                // 评论
                $res = $comment->insert_data($where);
                if (isset($res['msg'])) {
                    echo json_encode($res);exit;
                }else{
                    echo json_encode(msg_success("评论成功"));exit;
                }
            }



        }else{

            $this->error("发生错误", 'index/index/index');            
        }

    } 

    public function more()
    {
        if (request()->isAjax()) {
            $comment = new CommentModel();
            $reply   = new ReplyModel();
            $member  = new MemberModel();

            $id = input("param.id/d");
            if (empty($id)) {
                echo json_encode(msg_error("参数错误"));exit;
            }

            // 评论详情
            $info = $comment->get_info(['comment_id' => $id], "comment_id, user_id");

            $where = [
                'comment_id' => $id,
            ];
            $list = $reply->get_list($where, "create_time desc");

            // 回复为空
            if (empty($list)) {
                echo json_encode(3);
                exit;
            }

            // 获取列表
            foreach ($list as $k => $v) {

                if ($v['reply_type'] == 1) {
                    $list[$k]['replyname'] = $member->get_field(['user_id' => $info['user_id']], "nickname");
                }else{
                    $u_id = $reply->get_field(['reply_id' => $v['reply_pid']], "user_id");
                    $list[$k]['replyname'] = $member->get_field(['user_id' => $u_id], "nickname");
                }

                // 会员信息
                $list[$k]['userinfo'] = $member->get_info(['user_id' => $v['user_id']], "user_id, headpic, nickname");
            }

            // 拼接html
            $str = "";
            foreach ($list as $k => $v) {
                $str .= '<div class="reply discuss">
                            <div class="line"></div>
                            <div class="author">
                                <img src="/'.$v['userinfo']['headpic'].'" class="img-circle" alt="" width="40">
                                <span>'.$v['userinfo']['nickname'].'：@'.$v['replyname'].'</span>
                            </div>                                    
                            <div class="info">'.$v['content'].'</div>
                            <p class="other">
                                <span class="time">
                                    <i class="iconfont">&#xe6f1;</i>
                                    '.$v['create_time'].'</span>
                                <span class="like">
                                    <a href="javascript:;" class="like_count" data-id="'.$v['reply_id'].'">
                                        <i class="iconfont">&#xe61b;</i>（<em>'.$v['like_count'].'</em>）
                                    </a>
                                </span>
                                <span class="respon">
                                    <a href="javascript:;" class="sub-reply" data-reply="'.$v['reply_id'].'" data-comment="'.$id.'" data-type="2">回复</a>
                                </span>
                            </p>';
                $str .= '</div>';
            }
            
            echo $str;
            exit;

        }else{
            $this->error("发生错误", 'index/index/index');            
        }
   }   

   // 点赞评论
   public function like_count()
   {
        if (request()->isAjax()) {
            $comment = new CommentModel();

            $id = input("param.id/d");

            $info = $comment::get($id);
            if (empty($info)) {
                echo json_encode(3);
                exit;
            }

            $rearr = session("like");
            if (!empty($rearr)) {
                if (isset($rearr[$id])) {
                    if (time() - $rearr[$id] < 300) {
                        echo json_encode(1);
                        exit;
                    }
                }
            }else{
                $rearr = [];
            }

            $where = [
                'comment_id' => $id,
                'like_count' => $info['like_count']+1,
            ];

            $res = $comment->save_data($where);
            if (isset($res['msg'])) {
                echo json_encode(2);
                exit;
            }

            // 重置计时
            $rearr[$id] = time();
            session("like", $rearr);
            // 输出
            echo json_encode(1);
            exit;
        }else{
            $this->error("发生错误", 'index/index/index');            
        }
   }

   // 点赞回复
   public function like_reply()
   {
        if (request()->isAjax()) {
            $reply = new ReplyModel();

            $id = input("param.id/d");

            $info = $reply::get($id);
            if (empty($info)) {
                echo json_encode(3);
                exit;
            }

            $rearr = session("reply");
            if (!empty($rearr)) {
                if (isset($rearr[$id])) {
                    if (time() - $rearr[$id] < 300) {
                        echo json_encode(1);
                        exit;
                    }
                }
            }else{
                $rearr = [];
            }

            $where = [
                'reply_id' => $id,
                'like_count' => $info['like_count']+1,
            ];

            $res = $reply->save_data($where);
            if (isset($res['msg'])) {
                echo json_encode(2);
                exit;
            }

            // 重置计时
            $rearr[$id] = time();
            session("reply", $rearr);
            // 输出
            echo json_encode(1);
            exit;
        }else{
            $this->error("发生错误", 'index/index/index');            
        }
   }


    // 所有分类
    public function cateall()
    {
        $class = new ClassModel();

        $where = ['status' => 1];
        $order = "class_id asc";
        $field = "*";

        $list = $class->get_list($where, $order, $field);

        return $this->fetch('class', ['data' => $list]);
    }

    // 所有标签
    public function laball()
    {
        $label = new LabelModel();

        $where = ['status' => 1];
        $order = "label_id asc";
        $list  = $label->get_list($where, $order, $fields = "*");

        return $this->fetch('label', ['data' => $list]);
    }    
}
